package com.ljh.mboxvidoserver.console.shop.service.impl;

import com.ljh.mboxvidoserver.console.shop.dao.ShopRepository;
import com.ljh.mboxvidoserver.console.shop.dao.ShopRepository2;
import com.ljh.mboxvidoserver.console.shop.entity.Shop;
import com.ljh.mboxvidoserver.console.shop.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopRepository shopRepository;

    @Override
    public Page<Shop> findList(Shop shop, Pageable pageable) {
        return shopRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<Predicate>();
            if (!StringUtils.isEmpty(shop.getShopName())) {
                list.add(criteriaBuilder.like(root.get("shopName"),"%"+shop.getShopName()+"%"));
            }
            if (!StringUtils.isEmpty(shop.getShopNo())) {
                list.add(criteriaBuilder.like(root.get("shopNo"),"%"+shop.getShopNo()+"%"));
            }
            return query.where(list.toArray(new Predicate[list.size()])).getRestriction();
        }, pageable);
    }

    @Override
    public Shop findOne(Shop shop) {
        return shopRepository.findById(shop.getId()).get();
    }

    @Override
    public Shop insertOne(Shop shop) {
        return shopRepository.save(shop);
    }

    @Override
    public void deleteOne(Shop shop) {
        shopRepository.deleteById(shop.getId());
    }

    @Override
    public Shop updateOne(Shop shop) {
        return shopRepository.save(shop);
    }
}
